package sparkStream

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig, ProducerRecord}
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import org.apache.spark.streaming.{Seconds, StreamingContext}

import java.util.HashMap

object SparkKafka {
  def main(args: Array[String]): Unit = {
    /* spark streaming实现kafka的消费者
    1）构建sparkconf 本地运行，运行应用程序名称
    2）构建sparkstreaming ————》  streamingContext，加载配置
    3）kafka 配置 brokee，key value ，group id，消费模式
    4）spark 链接kafka 订阅，设置topic名字和策略，streamingcontext
    5）循环的形式 打印
    6）开启sparkstreamingcontext，监控
     */

    //
    //    1）构建sparkconf 本地运行，运行应用程序名称
    val conf = new SparkConf().setMaster("local[*]").setAppName("helloSparkKafka")

    val ssc = new StreamingContext(conf, Seconds(2))

    //spark 输出红色info信息  --》error
    ssc.sparkContext.setLogLevel("error")


    //    3）kafka 配置 broker，key value ，group id，消费模式
    val kfkaParms = Map[String, Object](
      "bootstrap.servers" -> "123.56.187.176:9092",
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      "group.id" -> "niit",
      "enable.auto.commit" -> (false: java.lang.Boolean)
    )
    //    4）spark 链接kafka 订阅，设置topic名字和策略，streamingcontext
    //topic name
    val topicName = Array("stuInfo")
    //      val topicName = Array("15test")
    val streamRdd = KafkaUtils.createDirectStream[String, String](
      ssc,
      PreferConsistent,
      Subscribe[String, String](topicName, kfkaParms)
    )

    //  producer 配置项
    val property = new HashMap[String, Object]()
    property.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.109.100:9092")
    property.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")
    property.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer")


    //时间窗口 1
    //streamRdd kafka 返回的数据 key，value 数据是value
    val res = streamRdd.map(_.value())
    val result = res.flatMap(_.split("\t")).map((_, 1)).reduceByKeyAndWindow(_ + _, Seconds(4), Seconds(4))
    result.foreachRDD(
      x => {
        println("-------数据是-------")
        x.foreach(
          obj => {
            println(obj)

            val producer = new KafkaProducer[String, String](property)
            producer.send(new ProducerRecord[String, String]("15homework", obj.toString))
            producer.close()
          }
        )
      }
    )




    //        streamRdd.foreachRDD(
    //          x=>{
    //            if (! x.isEmpty()){
    //              val line =x.map(_.value())  //匿名函数
    //              line.foreach(println)
    //            }
    //          }
    //        )
    //

    ssc.start()
    ssc.awaitTermination()


  }
}
